<?php

namespace card\api;

use card\models\Card;
use card\models\CardBatch;
use framework\common\BasicController;
use Yii;
use yii\data\ActiveDataProvider;
use yii\db\Exception;

class CardbatchController extends BasicController
{
    /**
     * 重写父类
     * @return [type] [description]
     */
    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        unset($actions['create']);
        unset($actions['update']);
        return $actions;
    }

    public function actionSearch()
    {
        //获取头部信息
        $headers = Yii::$app->getRequest()->getHeaders();
        //获取分页信息
        $pageSize = $headers->get('X-Pagination-Per-Page') ?? 20;
        //订单分组
        $keyword = Yii::$app->request->post('keyword', []);
        $AppID = Yii::$app->params['AppID'];
        $where = ['AppID' => $AppID, 'is_deleted' => 0];


        //创建时间区间
        $created_time_start = $keyword['created_time_start'] ?? false;
        if ($created_time_start > 0) {
            $where = ['and', $where, ['>=', 'created_time', $created_time_start]];
        }
        $created_time_end = $keyword['created_time_end'] ?? false;
        if ($created_time_end > 0) {
            $where = ['and', $where, ['<=', 'created_time', $created_time_end]];
        }

        //处理排序
        $sort = isset($keyword['sort']) && is_array($keyword['sort']) ? $keyword['sort'] : [];
        $orderBy = [];
        if (empty($sort)) {
            $orderBy = ['created_time' => SORT_DESC];
        } else {
            foreach ($sort as $key => $value) {
                $orderBy[$key] = $value === 'ASC' ? SORT_ASC : SORT_DESC;
            }
        }

        $data = new ActiveDataProvider(
            [
                'query' => CardBatch::find()
                    ->where($where)
                    ->orderBy($orderBy)
                    ->asArray(),
                'pagination' => ['pageSize' => $pageSize, 'validatePage' => false],
            ]
        );
        return $data;
    }


    public function actionCreate()
    {
        $post = \Yii::$app->request->post();
        $model = new CardBatch();
        $model->setScenario('create');
        $model->setAttributes($post);
        $model->AppID = \Yii::$app->params['AppID'];
        $transaction = Yii::$app->db->beginTransaction();
        $res = $model->save();
        if ($res) {
            $length = $post['length'];
            $perfix = $post['perfix'] ?? '';
            $start_index = $post['start_index'];
            $num = $post['num'];
            $col = ['number', 'password', 'card_batch_id', 'amount', 'left_amount', 'expire_day',
                'AppID', 'created_time', 'updated_time', 'status', 'page_id', 'name', 'end_time'];
            $row = [];
            $time = time();
            $end_time = $time + 60 * 60 * 24 * $model->expire_day;
            $index_length = $length - mb_strlen($perfix);
            if ($index_length <= 0) {
                $transaction->rollBack();
                Error('生成失败，超出长度限制');
            }
            for ($i = 0; $i < $num; $i++) {
                $number = $perfix . str_pad($start_index + $i, $index_length, '0', STR_PAD_LEFT);
                $password = strtoupper($this->generateRandStr(12));
                if (mb_strlen($number) > $length) {
                    $transaction->rollBack();
                    Error('生成失败，超出长度限制');
                }
                $row[] = [$number, $password, $model->id,
                    $model->amount, $model->amount, $model->expire_day, $model->AppID, $time, $time, 0, $model->page_id?:0, $model->name, $end_time];
            }
            $numbers = array_column($row, 0);
            $exist = Card::find()->where(['and', ['in', 'number', $numbers], ['is_deleted' => 0]])->one();
            if ($exist) {
                $transaction->rollBack();
                Error('生成失败，卡号重复');
            }
            $table_prefix = Yii::$app->db->tablePrefix;
            $table = $table_prefix . 'card';
            $result = Yii::$app->db->createCommand()->batchInsert($table, $col, $row)->execute();
            if ($result) {
                $transaction->commit();
                return $model->id;
            } else {
                $transaction->rollBack();
                Error('生成失败');
            }
        } else {
            Error($model->getErrorMsg());
        }
    }

    public static function generateRandStr($length)
    {
        //字符组合
        $str = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
        $str = '123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    public function actionView()
    {
        $id = Yii::$app->request->get('id', false);
        $where = ['id' => $id, 'is_deleted' => 0];
        $result = CardBatch::find()
            ->where($where)
            ->asArray()
            ->one();
        if (empty($result)) {
            Error('卡密批次不存在');
        }
        $result = str2url($result);
        return $result;
    }

    /**
     * 处理数据软删除
     * @return [type] [description]
     */
    public function actionDelete()
    {
        $get = \Yii::$app->request->get();
        $id = intval($get['id']);
        $model = CardBatch::findOne($id);
        if ($model) {
            $model->scenario = 'delete';
            $model->deleted_time = time();
            $model->is_deleted = 1;
            if ($model->save()) {
                return $model->is_deleted;
            } else {
                Error('删除失败，请检查is_deleted字段是否存在');
            }
        } else {
            Error('删除失败，数据不存在');
        }
    }
}
